package com.example.coffeeorder;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class CoffeeOrderApp extends JFrame {
    private JTextField nameField, addressField, phoneField;
    private JComboBox<String> coffeeTypeCombo;
    private JSpinner quantitySpinner;
    private JButton placeOrderButton, viewOrdersButton;
    private JTextArea orderDetailsArea;

    private static final String DB_URL = "jdbc:mysql://localhost:3306/coffee_shop";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    public CoffeeOrderApp() {
        setTitle("咖啡订单管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        initComponents();
        createDatabaseAndTable();
    }

    private void initComponents() {
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        add(mainPanel);

        // 表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("客户姓名:"), gbc);

        gbc.gridx = 1;
        nameField = new JTextField(20);
        formPanel.add(nameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("联系地址:"), gbc);

        gbc.gridx = 1;
        addressField = new JTextField(20);
        formPanel.add(addressField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("联系电话:"), gbc);

        gbc.gridx = 1;
        phoneField = new JTextField(20);
        formPanel.add(phoneField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(new JLabel("咖啡类型:"), gbc);

        gbc.gridx = 1;
        String[] coffeeTypes = {"美式咖啡", "拿铁", "卡布奇诺", "摩卡", "浓缩咖啡"};
        coffeeTypeCombo = new JComboBox<>(coffeeTypes);
        formPanel.add(coffeeTypeCombo, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(new JLabel("数量:"), gbc);

        gbc.gridx = 1;
        SpinnerModel quantityModel = new SpinnerNumberModel(1, 1, 10, 1);
        quantitySpinner = new JSpinner(quantityModel);
        formPanel.add(quantitySpinner, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        placeOrderButton = new JButton("提交订单");
        viewOrdersButton = new JButton("查看订单");
        buttonPanel.add(placeOrderButton);
        buttonPanel.add(viewOrdersButton);

        // 订单详情区域
        orderDetailsArea = new JTextArea(15, 40);
        orderDetailsArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(orderDetailsArea);

        // 添加到主面板
        mainPanel.add(formPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        placeOrderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                placeOrder();
            }
        });

        viewOrdersButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewOrders();
            }
        });
    }

    private void createDatabaseAndTable() {
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement()) {
            
            // 创建数据库
            String createDbSql = "CREATE DATABASE IF NOT EXISTS coffee_shop";
            stmt.executeUpdate(createDbSql);
            
            // 使用数据库
            stmt.execute("USE coffee_shop");
            
            // 创建订单表
            String createTableSql = "CREATE TABLE IF NOT EXISTS orders (" +
                    "id INT AUTO_INCREMENT PRIMARY KEY," +
                    "name VARCHAR(100) NOT NULL," +
                    "address VARCHAR(255) NOT NULL," +
                    "phone VARCHAR(20) NOT NULL," +
                    "coffee_type VARCHAR(50) NOT NULL," +
                    "quantity INT NOT NULL," +
                    "order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
                    ")";
            stmt.executeUpdate(createTableSql);
            
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void placeOrder() {
        String name = nameField.getText();
        String address = addressField.getText();
        String phone = phoneField.getText();
        String coffeeType = (String) coffeeTypeCombo.getSelectedItem();
        int quantity = (Integer) quantitySpinner.getValue();

        if (name.isEmpty() || address.isEmpty() || phone.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String sql = "INSERT INTO orders (name, address, phone, coffee_type, quantity) VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, name);
            pstmt.setString(2, address);
            pstmt.setString(3, phone);
            pstmt.setString(4, coffeeType);
            pstmt.setInt(5, quantity);
            
            pstmt.executeUpdate();
            
            JOptionPane.showMessageDialog(this, "订单提交成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            clearForm();
            viewOrders();
            
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "订单提交失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void viewOrders() {
        String sql = "SELECT * FROM orders ORDER BY order_time DESC";
        StringBuilder result = new StringBuilder();
        
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            result.append("订单列表:\n");
            result.append("ID\t客户姓名\t联系电话\t咖啡类型\t数量\t订单时间\n");
            result.append("------------------------------------------------------------\n");
            
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                String coffeeType = rs.getString("coffee_type");
                int quantity = rs.getInt("quantity");
                Timestamp orderTime = rs.getTimestamp("order_time");
                
                result.append(id).append("\t")
                      .append(name).append("\t")
                      .append(phone).append("\t")
                      .append(coffeeType).append("\t")
                      .append(quantity).append("\t")
                      .append(orderTime).append("\n");
            }
            
        } catch (SQLException ex) {
            ex.printStackTrace();
            result.append("获取订单列表失败: ").append(ex.getMessage());
        }
        
        orderDetailsArea.setText(result.toString());
    }

    private void clearForm() {
        nameField.setText("");
        addressField.setText("");
        phoneField.setText("");
        coffeeTypeCombo.setSelectedIndex(0);
        quantitySpinner.setValue(1);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                CoffeeOrderApp app = new CoffeeOrderApp();
                app.setVisible(true);
            }
        });
    }
}    